package com.ruoyi.controller.jpjs.dan;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ArrayUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.domain.jpjs.common.dan.Dan;
import com.ruoyi.domain.jpjs.common.dan.Inventory;
import com.ruoyi.domain.jpjs.common.dandetail.DanDetail;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.service.jpjs.dan.DanService;
import com.ruoyi.util.dan.ExportDanExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author C.fw
 * @explain 危大工程控制层
 * @since 2020/8/15 15:43
 */
@Controller
@RequestMapping("/danManage")
public class DanController extends BaseController {

    private String prefix = "jpjs/dan";

    @Autowired
    private DanService danService;

    @Value("${ruoyi.downloadProfile}")
    private String downloadProfile;

    /**
     * 跳转首页面
     */
    @GetMapping()
    public String danManage() {
        return prefix + "/danManage";
    }

    /**
     * 初始化:获取列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo selectDanList(@RequestParam Map<String, Object> map) {
        startPage();
        if (map.containsKey("programName")) {
            map.put("programName", map.get("programName").toString().trim().replaceAll(",", ""));
        }
        // 获取当前登录人对应的项目权限
        map.put("userId", ShiroUtils.getSysUser().getUserId());
        List<Dan> list = danService.getDanList(map);
        return getDataTable(list);
    }

    /**
     * 新增页面
     */
    @GetMapping("/add")
    public String addView(ModelMap mmp, String programName, String companyId, String proId) {
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyId);
        map.put("proId", proId);
        mmp.put("companyId", companyId);
        mmp.put("programId", proId);
        mmp.put("programName", programName);
        return prefix + "/danAdd";
    }

    /**
     * 详情页面 新增保存
     */
    @PostMapping("/save")
    @ResponseBody
    public AjaxResult save(@RequestParam("companyFile") MultipartFile[] companyFile, @RequestParam("expertFile") MultipartFile[] expertFile, Dan dan) {
        try {

            dan.setUpdateBy(ShiroUtils.getSysUser().getUserName());

            // Step2 新增并响应
            return toAjax(danService.insertDan(dan, companyFile, expertFile));

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 编辑页面
     */
    @GetMapping("/editListView")
    public String editListView(ModelMap mmp, String danId, String companyId, String programId) {
        mmp.put("danId", danId);
        mmp.put("companyId", companyId);
        mmp.put("programId", programId);
        Map<String, Object> map = new HashMap<>();
        map.put("danId", danId);
        mmp.put("dan", danService.getDanList(map).get(0));
        return prefix + "/danEdit";
    }

    /**
     * 编辑保存
     */
    @PostMapping("/updateDan")
    @ResponseBody
    public AjaxResult updateDan(@RequestParam("companyFile") MultipartFile[] companyFile, @RequestParam("expertFile") MultipartFile[] expertFile, Dan dan) {
        try {
            dan.setUpdateBy(ShiroUtils.getSysUser().getUserName());

            // Step2 新增并响应
            return toAjax(danService.updateDanInfo(dan, companyFile, expertFile));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(danService.deleteDanById(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 导出
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult exportDan(@RequestParam Map<String, Object> map) {

        // Step1 获取需要导出的数据
        List<Dan> list = danService.getDanList(map);
        String filePath = Global.getDownloadPath() + "危大工程报表.xls";
        try {
            if (!ArrayUtil.isEmpty(list)) {

                // Step2 自定义导出Excel
                FileOutputStream fout = new FileOutputStream(filePath);
                new ExportDanExcel().getValue(list, fout);
                fout.close();
            }
        } catch (Exception e) {
            error(e.getMessage());
        }
        return AjaxResult.success(0);
    }

    /**
     * 详情页面
     */
    @GetMapping("/detail/{danId}")
    public String filePathdetail(@PathVariable("danId") Long danId, ModelMap mmap) {
        mmap.put("danId", danId);
        return prefix + "/danDetail";
    }

    /**
     * 详情页面 初始化数据
     */
    @PostMapping("/detailList")
    @ResponseBody
    public TableDataInfo selectDanDetailList(DanDetail danDetail) {
        startPage();
        Map<String, Object> map = new HashMap<>();
        map.put("danId", danDetail.getDanId());
        List<DanDetail> list = danService.selectDanDetailInfo(map);
        return getDataTable(list);
    }

    /**
     * 详情页面 新增页面
     */
    @GetMapping("/detailAdd/{danId}")
    public String detailAdd(@PathVariable("danId") Long danId, ModelMap mmap) {
        mmap.put("danId", danId);
        return prefix + "/danDetailAdd";
    }

    /**
     * 详情页面 新增保存
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult updateAvatar(@RequestParam("file") MultipartFile file, DanDetail danDetail) {
        try {

            // Step1 物理上传
            String fileName = FileUploadUtils.upload(Global.getUploadPath(), file);

            // Step1.2 参数准备
            // 物理路径,用于物理删除
            danDetail.setPhysicalPath(getPhysicalPath(Global.getUploadPath(), fileName));
            // 文件名,用于下载
            danDetail.setFileName(fileName);
            // 虚拟路径,用于展示
            danDetail.setVirtualPath(ServerConfig.getUrl() + fileName);

            // Step2 新增并响应
            return toAjax(danService.insertDanDetail(danDetail));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    private String getPhysicalPath(String filePath, String fileName) {
        String replace = fileName.replace("/profile/upload", "");
        String physicalPath = filePath + replace;
        return physicalPath;
    }

    /**
     * 详情页面 编辑页面
     */
    @GetMapping("/detailEditView/{danDetailId}")
    public String detailEditView(@PathVariable("danDetailId") Long danDetailId, ModelMap mmap) {
        mmap.put("danDetailId", danDetailId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("danDetailId", danDetailId);
        mmap.put("danDetail", danService.selectDanDetailInfo(map).get(0));
        return prefix + "/danDetailEdit";
    }

    /**
     * 编辑删除附件
     */
    @RequestMapping("/detailEditView/deletePic")
    @ResponseBody
    public AjaxResult detail(DanDetail danDetail) {

        // Step1 根据ID进行物理删除
        Boolean flag = danService.deleteFilePathById(Long.valueOf(danDetail.getKey()));

        // Setp2 更新数据库响应
        if (flag) {
            return AjaxResult.success(danService.updatePathById(Long.valueOf(String.valueOf(danDetail.getKey()))));
        }
        return AjaxResult.error("失败");
    }

    /**
     * 详情页面 编辑保存
     * <p>
     * Tip  分两种情况
     * 编辑图片:之前需要删除图片,已经进行了物理删除,这里直接上传
     * 不编辑图片:直接上传
     */
    @PostMapping("/updateDanDetail")
    @ResponseBody
    public AjaxResult updateDanDetail(@RequestParam("file") MultipartFile file, DanDetail danDetail) {
        try {

            // Step1 物理上传
            String fileName = FileUploadUtils.upload(Global.getUploadPath(), file);

            // Step1.2 准备参数
            danDetail.setPhysicalPath(getPhysicalPath(Global.getUploadPath(), fileName));
            danDetail.setFileName(fileName);
            danDetail.setVirtualPath(ServerConfig.getUrl() + fileName);

            // Step2 更新响应
            return toAjax(danService.updateDanDetailById(danDetail));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 详情页面 删除
     */
    @PostMapping("/removeDetail")
    @ResponseBody
    public AjaxResult removeDetail(String ids) {
        try {
            return toAjax(danService.deleteDanDetailById(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 详情页面 导出
     */
    @PostMapping("/exportDetail")
    @ResponseBody
    public AjaxResult export(@RequestParam Map<String, Object> map) {
        // Step1 获取需要导出的数据
        List<DanDetail> list = danService.selectDanDetailInfo(map);

        // Step2 模板导出Excel
        ExcelUtil<DanDetail> util = new ExcelUtil<DanDetail>(DanDetail.class);
        return util.exportExcel(list, "危大详情");
    }

    /**
     * 初始化:获取树组件列表
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData(String menu) {
        return danService.getProgramTree(menu);
    }

    /**
     * 危大工程清单录入按钮 新增页面
     */
    @GetMapping("/addInventory")
    public String addInventory(ModelMap mmp, String programName, String companyId, String proId) {
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyId);
        map.put("proId", proId);
        mmp.put("companyId", companyId);
        mmp.put("programId", proId);
        mmp.put("programName", programName);
        return prefix + "/inventory";
    }

    /**
     * 危大工程清单录入按钮 新增保存
     */
    @PostMapping("/saveInventory")
    @ResponseBody
    public AjaxResult saveInventory(@RequestParam("file") MultipartFile file, Inventory inventory) {
        try {

            // Step1 物理上传
            String fileName = FileUploadUtils.upload(Global.getUploadPath(), file);

            // 文件名,用于下载
            inventory.setFileName(fileName);
            // 虚拟路径,用于展示
            inventory.setVirtualPath(ServerConfig.getUrl() + fileName);
            inventory.setDanId("0");

            // 类型为清单文件
            inventory.setType("0");

            // Step2 新增并响应
            return toAjax(danService.insertInventory(inventory));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/inventoryView")
    public String inventoryView(ModelMap mmp, String proId, String type, String danId) {
        mmp.put("programId", proId);
        mmp.put("type", type);
        mmp.put("danId", danId);
        return prefix + "/inventoryList";
    }

    @PostMapping("/selectInventoryList")
    @ResponseBody
    public TableDataInfo selectInventoryList(@RequestParam Map<String, Object> map) {
        startPage();
        // 获取当前登录人对应的项目权限
        map.put("userId", ShiroUtils.getSysUser().getUserId());

        List<Inventory> list = danService.getInventoryList(map);
        return getDataTable(list);
    }

    /**
     * 详情页面 删除
     */
    @PostMapping("/removeInventory")
    @ResponseBody
    public AjaxResult removeInventory(String ids) {
        try {
            return toAjax(danService.deleteInventoryById(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 本地资源路径
        String downloadPath = downloadProfile + Constants.PROJECT_FILE; // D:/ruoyi/uploadPath/upload/2021/01/20/50e41008f1575ef254c0486c2f1b44c6.xlsx
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/"); // 50e41008f1575ef254c0486c2f1b44c6.xlsx
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }


}
